package xyz.xpman.prisonerfitness.config;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import xyz.xpman.prisonerfitness.R;
import xyz.xpman.prisonerfitness.kit.QQKitProxy;
import xyz.xpman.prisonerfitness.util.FileUtil;
import xyz.xpman.prisonerfitness.util.StrKit;
import xyz.xpman.prisonerfitness.util.StreamUtils;
import xyz.xpman.prisonerfitness.util.XmlUtil;


public class AppConfig {
    private static final String CONFIG_FILE_NAME = "app_config.xml";
    private static final String DEFAULT_MUSIC_RELATIVE_DIR_NAME = "/music";
//    private static final String DEFAULT_MUSIC_RELATIVE_FILE_NAME = "/default_bg_music.mp3";
    private static final String DEFAULT_MUSIC_RELATIVE_FILE_NAME = "/bengbengca.mp3";

    private static final String VOLUME = "volume";
    private static final String BG_MUSIC = "bg_music";
    private static final String GROUP_REST_INTERVAL = "groupRestInterval";
    private static final String UP_AND_DOWN_INTERVAL = "upAndDownInterval";
    @SuppressLint("StaticFieldLeak")
    private static Context context = null;

    private static int volume = 25;
    private static int upAndDownInterval = 30;
    private static int groupRestInterval = 450;

    private static String musicFileDir = "";
    private static String musicFileName = "";
    private static String decodeMusicFileName = "";
    private static String defaultMusicFileName = "";

    private AppConfig() { }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void init(@NotNull Context context) {
        if (null == AppConfig.context) {
            AppConfig.context = context;
            initConfig();
            initMusic();
            initQQConfig();
        }
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    private static void initQQConfig() {
        final String json = StreamUtils.get(context, R.raw.qq);
        QQConfig config = QQConfig.EMPTY;

        try {
            config = QQConfig.byJson(new JSONObject(json));
        } catch (Exception ignored) { }

        QQKitProxy.init(config);
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void initConfig() {
        try (FileInputStream fis = context.openFileInput(CONFIG_FILE_NAME)) {
            Map<String, String> data = XmlUtil.parseToMap(fis);

            if (data.isEmpty()) {
                save();
                return;
            }

            setVolume(data.get(VOLUME));
            setBgMusicFileName(data.get(BG_MUSIC));
            setGroupRestInterval(data.get(GROUP_REST_INTERVAL));
            setUpAndDownInterval(data.get(UP_AND_DOWN_INTERVAL));

        } catch (IOException ignored) { }
    }

    private static void initMusic() {
        musicFileDir = context.getFilesDir().getAbsolutePath()
                + DEFAULT_MUSIC_RELATIVE_DIR_NAME;

        final String temp = musicFileDir + DEFAULT_MUSIC_RELATIVE_FILE_NAME;

        musicFileName = temp;
        decodeMusicFileName = temp;
        defaultMusicFileName = temp;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static boolean save() {
        final Map<String, String> data = new HashMap<>();

        data.put(BG_MUSIC, musicFileName);
        data.put(VOLUME, String.valueOf(volume));
        data.put(UP_AND_DOWN_INTERVAL, String.valueOf(upAndDownInterval));
        data.put(GROUP_REST_INTERVAL, String.valueOf(groupRestInterval));

        String dataString = XmlUtil.toXmlString(data);
        checkConfigFileExist();
        boolean success = false;

        try (FileOutputStream fos = context.openFileOutput(CONFIG_FILE_NAME, Context.MODE_PRIVATE)) {

            success = StreamUtils.write(fos, dataString);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return success;
    }


    private static void checkConfigFileExist() {
        String fileName = context.getFilesDir() + "/" + CONFIG_FILE_NAME;

        if (!FileUtil.isFileExists(fileName)) {
            FileUtil.createFile(new File(fileName));
        }
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    /**
     * 获取训练音量
     * @return [0 - 100]
     */
    public static int getVolume() {
        return volume;
    }

    public static void setVolume(int volume) {
        AppConfig.volume = volume;
    }

    private static void setVolume(String volume) {
        if (StrKit.notBlank(volume)) {
            try {
                AppConfig.volume = Integer.parseInt(volume);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取上下动作时间间隔
     * 单位为百毫秒，如值45为4.5秒
     * @return 时间间隔
     */
    public static int getUpAndDownInterval() {
        return upAndDownInterval;
    }

    public static void setUpAndDownInterval(int upAndDownInterval) {
        AppConfig.upAndDownInterval = upAndDownInterval;
    }

    private static void setUpAndDownInterval(String str) {
        if (StrKit.notBlank(str)) {
            try {
                AppConfig.upAndDownInterval = Integer.parseInt(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 获取组间休息时间间隔
     * 单位为百毫秒，如值45为4.5秒
     * @return 时间间隔
     */
    public static int getGroupRestInterval() {
        return groupRestInterval;
    }

    public static void setGroupRestInterval(int groupRestInterval) {
        AppConfig.groupRestInterval = groupRestInterval;
    }

    private static void setGroupRestInterval(String str) {
        if (StrKit.notBlank(str)) {
            try {
                AppConfig.groupRestInterval = Integer.parseInt(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    public static String getMusicFileDir() {
        return musicFileDir;
    }

    public static String getBgMusicFileDir() {
        File file = new File(AppConfig.getBgMusicFileName());
        Log.i("AppConfig", "defaultMusicFileName: " + defaultMusicFileName);

        if (defaultMusicFileName.equals(getBgMusicFileName())) {
            return "";
        }
        return file.getParent();
    }

    public static String getBgMusicFileName() {
        return musicFileName;
    }

    public static String getDecodeBgMusicFileName() {
        return decodeMusicFileName;
    }

    public static void setBgMusicFileName(String musicFileName) {
        if (StrKit.notBlank(musicFileName)) {
            AppConfig.musicFileName = musicFileName;

            try {
                AppConfig.decodeMusicFileName =
                        URLDecoder.decode(musicFileName, "utf-8");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

}
